package com.sky.service.impl;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;


    @Autowired
    private WorkSpaceService workSpaceService;

@Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime",beginTime);
            map.put("endTime", endTime);
            Double turnover = orderMapper.sumByDate(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserData(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end))
        {
            dateList.add(begin);
            begin=begin.plusDays(1);

        }
        List<Integer> newUserDayList = new ArrayList<>();
        List<Integer> totalUserDayList=new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser =getUserCount(beginTime,endTime);
            newUserDayList.add(newUser);
            Integer totalUser=getUserCount(null,endTime);
            totalUserDayList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserDayList,","))
                .totalUserList(StringUtils.join(totalUserDayList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderData(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end))
        {
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer order = getOrder(beginTime, endTime, null);
            orderCountList.add(order);
            Integer validOrder = getOrder(beginTime, endTime, 1);
            validOrderCountList.add(validOrder);
        }
        Integer orderSum = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderSum = validOrderCountList.stream().reduce(Integer::sum).get();
        Double rate=new Double(0);
        if(orderSum!=0)
        {
            rate=validOrderSum.doubleValue()/orderSum;

        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(orderSum)
                .orderCompletionRate(rate)
                .validOrderCount(validOrderSum)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> topdataList = orderMapper.getTop10(beginTime, endTime);
        List<String> nameList = topdataList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> nubmerList = topdataList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(nubmerList,","))
                .build();

    }

    @Override
    public void export(HttpServletResponse httpServletResponse)  {

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN),LocalDateTime.of(dateEnd,LocalTime.MAX));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间"+dateBegin+"至"+dateEnd);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获得第五行
            XSSFRow row1 = sheet.getRow(4);
row1.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
row1.getCell(4).setCellValue(businessDataVO.getUnitPrice());
//填充明细
            for (int i = 0; i < 30; i++) {
                LocalDate begin = dateBegin.minusDays(1);
                BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
          //获取某一行
                XSSFRow row2 = sheet.getRow(7 + i);
                row2.getCell(1).setCellValue(begin.toString());
                row2.getCell(2).setCellValue(businessData.getTurnover());
                row2.getCell(3).setCellValue(businessData.getValidOrderCount());
                row2.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row2.getCell(5).setCellValue(businessData.getUnitPrice());
                row2.getCell(6).setCellValue(businessData.getNewUsers());


            }
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.close();
            excel.close();


        }catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    private Integer getOrder(LocalDateTime begin, LocalDateTime end,Integer status)
    {
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.countOrder(map);
    }

    private Integer getUserCount(LocalDateTime begin, LocalDateTime end)
    {
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        return orderMapper.countByMap(map);
    }
}
